//
//  NetworkTools.swift
//  Microblog
//
//  Created by steaest on 15/7/31.
//  Copyright © 2015年 steaest. All rights reserved.
//

import UIKit
import AFNetworking

//错误的类别标记
private let ErrorDomainName = "cn.steaest.error.Network"

private enum WWNetworkError: Int {

    case emptyDataError = -1
    case emptyTokenError = -2
    
    //错误描述
    private var errorDescrption: String {
        switch self {
        case .emptyDataError: return "空数据"
        case .emptyTokenError: return "Token为空"
        }
    }
    
    //根据枚举类型,返回对应的错误
    private func error() -> NSError {
        return NSError(domain: ErrorDomainName, code: rawValue, userInfo: [ErrorDomainName: errorDescrption])
    }
}

//网络访问方法
private enum NetworkMethod: String {

    case GET = "GET"
    case POST = "POST"
}


class NetworkTools: AFHTTPSessionManager {
    
    //应用程序信息
    private let clientId = "276318091"
    private let appSecret = "197b2a47a4782fa6a8f67a68c3a81311"
    //回调地址
    let redirectUri = "http://www.baidu.com"
    
    //网络单例
    static let sharedTools: NetworkTools = {
    
        let baseURL = NSURL(string: "https://api.weibo.com/")!
        let tools = NetworkTools(baseURL: baseURL)
        
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject> 
        
        return tools
    }()
    
    //MARK: - 检查并生成token字典,包含错误回调
    private func tokenDict(finished: NetFinishedCallBack) -> [String: AnyObject]? {
    
        if UserAccount.sharedAccount?.access_token == nil {
            
            let error = WWNetworkError.emptyTokenError.error()
        
            print(error)
            
            return nil
        }
        
        //不为空,生成 token 字典返回
        return ["access_token": UserAccount.sharedAccount!.access_token!]
    
    }
    
    //MARK: - 加载用户数据
    //1.加载用户信息 做网络访问,获取网络返回的用户字典
    // uid      用户代号字符串
    // params   回调

    func loadUserInfo(uid: String, finished: NetFinishedCallBack) {
        
        //guard
        guard var params = tokenDict(finished) else {
            return
        }
    
        let urlString = "2/users/show.json"
        //拼接
        params["uid"] = uid
        //发送网络请求 出现错误一般式参数格式不匹配
        request(NetworkMethod.GET, urlString: urlString, params: params, finished: finished)
    }
    
    //MARK: - 加载微博数据
    /**
        since_id    则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0
        max_id      则返回ID`小于或等于max_id`的微博，默认为0
    */
    func loadStatus(since_id: Int,max_id: Int, finished: NetFinishedCallBack) {
        
        guard var params = tokenDict(finished) else {
            return
        }
        
        if since_id > 0 {
            params["since_id"] = since_id
        }
        
        if max_id > 0 {
            params["max_id"] = max_id - 1
        }
        
        let urlString = "2/statuses/home_timeline.json"
        request(NetworkMethod.GET, urlString: urlString, params: params, finished: finished)
    }
    
     //MARK: - OAuth授权
    //返回授权地址
    func oauthUrl() -> NSURL {
    
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
   
        return NSURL(string: urlString)!
    }
    
    //MARK: - 加载token
    func loadAccessToken(code: String, finished: (result: [String: AnyObject]?, error: NSError?) ->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id":clientId,
                    "client_secret":appSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirectUri]
        
        //自定义封装方法
        request(NetworkMethod.POST, urlString: urlString, params: params, finished: finished)
    }
    
    //
    typealias NetFinishedCallBack = (result: [String: AnyObject]?, error: NSError?) ->()
    
    //MARK: - 封装AFN方法,便于替换网络访问方法,第三方框架代码在次集中
    /// AFN 网络请求 GET / POST
    ///
    /// :param: method    HTTP 方法 GET / POST
    /// :param: urlString URL 字符串
    /// :param: params    字典参数
    /// :param: finished  完成回调
    private func request(method: NetworkMethod, urlString: String, params: [String: AnyObject], finished: NetFinishedCallBack) {
    
        //定义成功的回调
        let successCallBack: (NSURLSessionDataTask!,AnyObject!) -> Void = { (_,JSON) -> Void in
        
            if let result = JSON as? [String: AnyObject] {
            
                //有结果的回调
                finished(result: result, error: nil)
            } else {
            
                print("没有数据 \(method) Request \(urlString)")
                finished(result: nil, error: WWNetworkError.emptyDataError.error())
            }
        }
        
        //定义失败的回调
        let failedCallBack: (NSURLSessionDataTask!,NSError!) -> Void = { (_,error) -> Void in
            
            print(error)
            finished(result: nil, error: error)
        }
        
        //根据枚举类型选择请求方式
        switch method {
        case .GET:
            GET(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
            case .POST:
            POST(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        }
    }
    
}
